<template>
  <div class="Roles-container">
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button
            type="primary"
            @click="addDialogVisible=true"
          >添加角色按钮</el-button>
        </el-col>
      </el-row>
      <el-table
        :data="rolesList"
        border
        stripe
        style="width: 100%"
      >
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', i1===0? 'bdtop':'']"
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
              class="vcenter"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightBbyId(scope.row,item1.id)"
                >{{item1.authName}}</el-tag>
                <i class="el-icon-arrow-right"></i>
              </el-col>
              <!-- 渲染二级权限 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                  :class="[ i2===0? '':'bdtop']"
                  class="vcenter"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightBbyId(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-arrow-right"></i>
                  </el-col>
                  <!-- 渲染三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      v-for="(item3, i3) in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="removeRightBbyId(scope.row,item3.id)"
                    >
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>

              </el-col>
            </el-row>

          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column
          type="index"
          label="#"
        ></el-table-column>
        <el-table-column
          prop="roleName"
          label="角色名称"
        >
        </el-table-column>
        <el-table-column
          prop="roleDesc"
          label="角色描述"
        >
        </el-table-column>
        <el-table-column
          prop="level"
          label="操作"
        >
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              v-model="scope.row.roleName"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            >编辑</el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              v-model="scope.row.roleName"
              size="mini"
              @click="removeRolesById(scope.row.id)"
            >删除</el-button>
            <el-tooltip
              effect="dark"
              content="角色分配"
              placement="top-start"
              :enterable="false"
            >
              <!-- 角色分配按钮 -->
              <el-button
                type="warning"
                icon="el-icon-setting"
                v-model="scope.row.roleName"
                size="mini"
                @click="showSetRightDialog(scope.row)"
              >分配权限</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 添加角色主体内容区域 -->
      <el-form
        :model="addRolesFrom"
        :rules="addRolesFromRules"
        ref="addRolesFromRef"
        label-width="70px"
      >
        <el-form-item
          label="角色名"
          prop="roleName"
        >
          <el-input v-model="addRolesFrom.roleName"></el-input>
        </el-form-item>
        <el-form-item
          label="描述"
          prop="roleDesc"
        >
          <el-input v-model="addRolesFrom.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="addRoles"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色对话框 -->
    <el-dialog
      title="修改角色"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed "
    >
      <!-- 修改角色主体内容区域 -->
      <el-form
        :model="editRolesFrom"
        :rules="editRolesFromRules"
        ref="editRolesFromRef"
        label-width="70px"
      >
        <el-form-item
          label="id"
          prop="roleId"
        >
          <el-input v-model="editRolesFrom.roleId"></el-input>
        </el-form-item>
        <el-form-item
          label="角色名"
          prop="roleName"
        >
          <el-input v-model="editRolesFrom.roleName"></el-input>
        </el-form-item>
        <el-form-item
          label="描述"
          prop="roleDesc"
        >
          <el-input v-model="editRolesFrom.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="editRolesInfo()"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="权限分配"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClosed"
    >
      <!-- 树形控件区域 -->
      <el-tree
        :data="rightslist"
        :props="treeProps"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="allotRights"
        >确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  data() {
    return {
      // 所有角色列表数据
      rolesList: [],
      // 控制添加删除用户对话框的显示与隐藏
      addDialogVisible: false,
      // 添加角色的表单数据
      addRolesFrom: {
        roleName: ""
      },
      //  添加表单的验证规则对象
      addRolesFromRules: {
        roleName: [
          { required: true, message: "请输入角色名", tirgger: "blur" },
          {
            min: 3,
            max: 10,
            message: "角色名的长度在3到10个字符之间",
            tirgger: "blur"
          }
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", tirgger: "blur" },
          {
            min: 5,
            max: 15,
            message: "角色名的长度在5到15个字符之间",
            tirgger: "blur"
          }
        ]
      },
      // 修改角色对话框的显示与隐藏
      editDialogVisible: false,
      // 查询到的角色信息
      editRolesFrom: {},
      // 编辑角色的验证规则
      editRolesFromRules: {
        roleName: [
          { required: true, message: "请输入角色名", tirgger: "blur" },
          {
            min: 3,
            max: 10,
            message: "角色名的长度在3到10个字符之间",
            tirgger: "blur"
          }
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", tirgger: "blur" },
          {
            min: 5,
            max: 15,
            message: "角色名的长度在5到15个字符之间",
            tirgger: "blur"
          }
        ]
        // : [
        //   { required: true, message: '请输入角色id', tirgger: 'blur' },
        //   { min: 1, max: 3, message: '角色名的长度在5到15个字符之间', tirgger: 'blur' }
        // ]
        // roleId: []
      },
      // 分配权限对话框的显示与隐藏
      setRightDialogVisible: false,
      // 所有权限数据
      rightslist: [],
      // 树形控件对象
      treeProps: {
        children: "children",
        label: "authName"
      },
      // 默认选中的节点id值 数组
      defKeys: [],
      // 即将分配权限的角色id
      roleId: ""
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get("roles")
      if (res.meta.status !== 200) {
        return this.Message.error("获取角色列表失败！")
      }
      this.rolesList = res.data
    },
    // 可以发起角色请求
    async addRoles() {
      const { data: res } = await this.$http.post("roles", this.addRolesFrom)
      if (res.meta.status !== 201) {
        return this.$Message.error("添加角色失败")
      }
      this.addDialogVisible = false
      this.$Message.success("添加角色成功")
      // 重新获取角色信息
      this.getRolesList()
    },
    // 添加角色对话框的重置功能
    addDialogClosed() {
      this.$refs.addRolesFromRef.resetFields()
    },
    // 展示编辑角色的对话框
    async showEditDialog(id) {
      const { data: res } = await this.$http.get("roles/" + id)
      if (res.meta.status !== 200) {
        return this.$Message.error("查询角色信息失败")
      }
      this.editRolesFrom = res.data
      this.editDialogVisible = true
    },
    // 编辑角色对话框的关闭事件
    editDialogClosed() {
      this.$refs.editRolesFromRef.resetFields()
    },
    // 修改角色信息并提交
    editRolesInfo() {
      // 发起修改角色信息的数据请求
      this.$refs.editRolesFromRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          "roles/" + this.editRolesFrom.roleId,
          {
            roleName: this.editRolesFrom.roleName,
            roleDesc: this.editRolesFrom.roleDesc,
            roleId: this.editRolesFrom.roleId
          }
        )
        if (res.meta.status !== 200) {
          console.log(this.editRolesFrom.roleId)
          return this.$Message.error("修改角色信息失败")
        }
        // 关闭对话框
        this.editDialogVisible = false
        // 刷新角色信息
        this.getRolesList()
        // 提示成功
        this.$Message.success("修改角色信息成功")
      })
    },
    // 根据id删除对应的角色信息
    async removeRolesById(id) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err)
      // 如果用户确认删除则返回值为字符串 confirm
      // 如果用户取消删除这返回值为字符串 cancel
      // console.log(confirmResult)
      if (confirmResult !== "confirm") {
        return this.$Message.info("已经取消删除")
      }
      console.log("确认删除")
      const { data: res } = await this.$http.delete("roles/" + id)
      if (res.meta.status !== 200) {
        return this.$Message.error("删除失败")
      }
      this.$Message.success("删除成功")
      // 删除之后刷新数据列表
      this.getRolesList()
    },
    // 根据id删除对应权限
    async removeRightBbyId(role, rightId) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(error => error)
      if (confirmResult !== "confirm") {
        return this.$Message.info("取消了删除")
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) {
        return this.$Message.error("删除角色权限失败")
      }
      this.$Message.success("删除角色权限成功")
      // 删除之后重新权限数据
      role.children = res.data
    },
    // 展示分配权限对话框
    async showSetRightDialog(role) {
      this.roleId = role.id
      // 获取所有权限数据
      const { data: res } = await this.$http.get("rights/tree")
      if (res.meta.status !== 200) {
        return this.$Message.error("获取权限数据失败")
      }
      // 把获取到的所有权限数据保存到data中
      this.rightslist = res.data
      // 递归获取三级节点的id
      this.getLeafKeys(role, this.defKeys)
      this.setRightDialogVisible = true
    },
    // 通过递归 的形式 获取角色下所有三级权限的id 并保存到deKeys数组中
    getLeafKeys(node, arr) {
      // 如果当前node节点不包含children属性 则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 监听分配权限对话框的关闭事件
    setRightDialogClosed() {
      this.defKeys = []
    },
    // 点击为角色分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      console.log(keys)
      const idStr = keys.join(",")
      console.log(idStr)
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      )
      if (res.meta.status !== 200) {
        return this.$Message.error("权限分配失败")
      }
      this.$Message.success("权限分配成功")
      this.getRolesList()
      this.setRightDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
